package com.vast.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vast.admin.mapper.ManagerCompanyDataMapper;
import com.vast.admin.entity.ManagerCompanyData;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ManagerCompanyDataService extends ServiceImpl<ManagerCompanyDataMapper, ManagerCompanyData> {

    /**
     * 保存用户企业数据权限
     * @param managerId
     * @param managerCompanyDatas
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(Long managerId, ManagerCompanyData[] managerCompanyDatas) {
        QueryWrapper<ManagerCompanyData> deleteQueryWrapper = new QueryWrapper<>();
        deleteQueryWrapper.eq(ManagerCompanyData.COL_MANAGER_ID, managerId);
        super.remove(deleteQueryWrapper);
        if (managerCompanyDatas != null && managerCompanyDatas.length > 0) {
            for (ManagerCompanyData managerCompanyData : managerCompanyDatas) {
                managerCompanyData.setManagerId(managerId);
            }
        }
        super.saveBatch(Arrays.asList(managerCompanyDatas));
    }

    /**
     * 通过managerId获取
     * @param managerId
     * @return
     */
    public ManagerCompanyData[] getByManagerId(Long managerId) {
        QueryWrapper<ManagerCompanyData> managerCompanyDataQueryWrapper = new QueryWrapper<>();
        managerCompanyDataQueryWrapper.eq(ManagerCompanyData.COL_MANAGER_ID, managerId);
        List<ManagerCompanyData> managerCompanyDataList = super.list(managerCompanyDataQueryWrapper);
        ManagerCompanyData[] managerCompanyDatas;
        if (managerCompanyDataList != null && !managerCompanyDataList.isEmpty()) {
            managerCompanyDatas = new ManagerCompanyData[managerCompanyDataList.size()];
            managerCompanyDatas = managerCompanyDataList.toArray(managerCompanyDatas);
        } else {
            managerCompanyDatas = new ManagerCompanyData[0];
        }
        return managerCompanyDatas;
    }

    /**
     * 获取企业ID
     * @param managerId
     * @return
     */
    public List<Long> getCompanyIdsByManagerId(Long managerId) {
        List<Long> companyIds = null;
        if (managerId != null) {
            for (ManagerCompanyData managerCompanyData : getByManagerId(managerId)) {
                if (companyIds == null) {
                    companyIds = new ArrayList<>();
                }
                companyIds.add(managerCompanyData.getCompanyId());
            }
        }
        return companyIds;
    }
}
